import React, { useEffect, useState, Component } from 'react';
import styles from './login.less';
import { request } from '@/utils/request';
import { history } from 'umi';
import { connect, router } from 'dva';
import {
  Menu, Switch, Divider, Checkbox, Button, Row, Col, Tooltip, notification,
  Form, Modal, Select, Tree, Icon, Radio, Table, Tag, Pagination, Input, Space, message, Card
} from 'antd';
import { MailOutlined, AppstoreOutlined, SettingOutlined, AudioOutlined, } from '@ant-design/icons';
import { set } from 'lodash';
import { findUserByUsername, findUsers, addUser } from '@/utils/loginAssert';


// dbms.active_database=graph3.db
const { SubMenu } = Menu;
const { Option } = Select;

const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};
const tailLayout = {
  wrapperCol: { offset: 8, span: 16 },
};

export default () => {

  //初始函数
  useEffect(() => {
    //此处编写 组件挂载之后和组件重新渲染之后执行的代码

    return () => {
      //此处编写 组件即将被卸载前执行的代码
    }
    // 4、若传值，但是传的是空数组 []，则表示该useEffect里的内容仅会在“挂载完成后和组件即将被卸载前”执行一次；
  }, [])

  const onFinish = (values) => {
    console.log('Success:', values);
    const { username, password } = values;
    let user = findUserByUsername(username);
    if (user) {
      // message.info('用户已存在，无需注册！')
      console.log('psw', user.password)
    } else {
      // localStorage.setItem('users',JSON.stringify([...users, {username,password}]));
      addUser({ username, password })
      message.info('Congraduaction，registry success！')
      history.push('/user/login')
    }
  };

  // java 后端注册
  const onFinishApi = (values) => {
    const { username, password } = values;
    let user = findUserByUsername(username);
    if (user) {
      message.info('user exist！')
      console.log('psw', user.password)
    } else {
      request(`/api/user_route/register`, {
        method: 'POST',
        data: { ...values, role: 'common' }
      }).then(res => {
        const { success, data } = res
        console.log(res)
        if (success && data) {
           addUser({ username, password })
            message.info('congraduations, please login', ()=>{
            history.push('/user/login')
          })
        } else {
          message.warning('registry fail!')
        }
      })
    }
  }


  const onFinishFlask = (values) => {
    const { username, password } = values;
    let user = findUserByUsername(username);
    if (user) {
      // message.info('用户已存在，无需注册！')
      console.log('psw', user.password)
    } else {
      request(`/flask/user_route/register`, { method: 'post', data: { ...values } }).then(res => {
        const { success } = res
        console.log(res)
        if (success) {
          addUser({ username, password })
          // message.info('恭喜你，注册成功，快去登录吧！')
          history.push('/user/login')
        } else {
          message.warning('registry fail!')
        }
      })
    }
  }

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  return (
    <>
      <div className={styles.login}>
        <Form
          {...layout}
          name="basic"
          initialValues={{
            remember: true,
          }}
          onFinish={onFinishApi}
          onFinishFailed={onFinishFailed}
        >
          <Form.Item
            label="Username"
            name="username"
            rules={[
              {
                required: true,
                message: 'Please input your username!',
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="Password"
            name="password"
            rules={[
              {
                required: true,
                message: 'Please input your password!',
              },
            ]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item >
            <Button type="primary" htmlType="submit">Registry</Button>
          </Form.Item>
        </Form>

      </div>

    </>
  );
}
